#include "daemon_process.h"
#include <stdlib.h>
#include <sys/wait.h>
#include "log/log.h"
#include <sys/types.h>
#include <signal.h>
#include <string.h>
#include <sys/reboot.h>

DaemonProcess *daemon_process_init(char *part)
{
    DaemonProcess *process = malloc(sizeof(DaemonProcess));
    if (!process)
    {
        goto PROCESS_MALLOC_FAIL;
    }

    process->cmd = "/usr/bin/gateway";
    process->args = malloc(sizeof(char *) * 3);
    if (!process->args)
    {
        goto ARGS_MALLOC_FAIL;
    }

    process->args[0] = process->cmd;
    process->args[1] = malloc(strlen(part));
    if (!process->args[1])
    {
        goto ARG_MALLOC_FAIL;
    }

    strcpy(process->args[1], part);
    process->args[2] = NULL;
    process->pid = -1;
    process->fail_count = 0;

    return process;
ARG_MALLOC_FAIL:
    free(process->args);
ARGS_MALLOC_FAIL:
    free(process);
PROCESS_MALLOC_FAIL:
    return NULL;
}

int daemon_process_start(DaemonProcess *process)
{
    int status = 0;
    if (process->pid != -1 && waitpid(process->pid, &status, WNOHANG) == 0)
    {
        return 0;
    }

    if (status != 0)
    {
        process->fail_count++;
        if (process->fail_count > 20)
        {
            reboot(RB_AUTOBOOT);
        }
    }

    // 进程未启动
    process->pid = fork();
    if (process->pid > 0)
    {
        // 父进程
        log_info("Process %s started", process->args[1]);
        return 0;
    }
    else if (process->pid == 0)
    {
        // 子进程
        execve(process->cmd, process->args, __environ);
        log_error("Process %s exec failed", process->args[1]);
        exit(-1);
    }
    else
    {
        log_error("Process %s fork failed", process->args[1]);
        return -1;
    }
}

int daemon_process_stop(DaemonProcess *process)
{
    if (kill(process->pid, SIGTERM) > 0)
    {
        waitpid(process->pid, NULL, 0);
        log_info("Process %s stopped", process->args[1]);
        return 0;
    }
    else
    {
        log_error("Process %s stop failed", process->args[1]);
        return -1;
    }
}
